
package com.netease.xone.fragment;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.AppInfo;
import protocol.meta.AppInfoDetail;
import protocol.meta.InfoComment;
import protocol.meta.InfoForward;
import protocol.meta.InfoPraise;
import protocol.meta.PageParam;
import protocol.transactions.TransactionGetInfoCfp;
import Utils.StackTraceUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.OnPinnedHeaderListener;
import com.handmark.pulltorefresh.library.X1LoadingAdapterViewBase.OnLoadingListener;
import com.netease.framework.widget.CustomAlertDialog;
import com.netease.log.NTLog;
import com.netease.pkgRelated.XoneConsts;
import com.netease.share.ShareBind;
import com.netease.share.ShareType;
import com.netease.share.db.ManagerShareBind;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityDetailMenuContainer;
import com.netease.xone.activity.ActivityDiscuss;
import com.netease.xone.activity.ActivityShare;
import com.netease.xone.activity.ActivityWBBind;
import com.netease.xone.adapter.AdapterInfoComment;
import com.netease.xone.adapter.AdapterInfoForward;
import com.netease.xone.adapter.AdapterInfoPraise;
import com.netease.xone.app.XoneApp;
import com.netease.xone.dataMgr.ParcelableArgument;
import com.netease.xone.itemview.IRenderInfoBase;
import com.netease.xone.itemview.RenderInfoBase;
import com.netease.xone.view.InfoDetailMoreMenu;
import com.netease.xone.widget.CustomDialog.OnCustomDlgCancelListener;
import com.netease.xone.widget.listview.LoadingListView;
import com.netease.xone.widget.listview.MultiAdapterManager;
import com.netease.xone.widget.tabview.AbsTabView.OnTabSelectListener;
import com.netease.xone.widget.tabview.TabInfoDetail;
import com.netease.xone.widget.tabview.TabInfoDetailMenu;

import db.manager.ManagerAccount;

public class FragmentInfoDetail extends FragmentAudioBase implements OnClickListener {
    private static final String TAG = FragmentInfoDetail.class.getSimpleName();

    public static FragmentInfoDetail newInstance(String infoId) {
        FragmentInfoDetail f = new FragmentInfoDetail();
        Bundle b = new Bundle();
        b.putString(XoneConsts.BUNDLE_KEY.INFO_ID, infoId);
        f.setArguments(b);
        return f;
    }

    public interface Menu {
        int comment = 0;
        int forward = 1;
        int praise  = 2;
        int more    = 3;
    }

    // 赞标志
    private boolean mPraiseFlag = false;
    // 聚焦位置，为了定位是在评论、转发还是赞
    private int    mIndex;
    // 资讯类别，官方和讨论, 默认讨论，正真的值要数据返回后确定
    private int  mInfoType = AppInfo.TYPE_DISCUSS;
    private int mTid = 0;
    private String mInfoId;
    private LinkedList<Integer> mReqList = new LinkedList<Integer>();
    private LoadingListView mListView;
    // 分享类型
    private ShareType mShareType;
    
    /**
     * 导航Tab
     */
    private TabInfoDetail mTabInfoHead;
    private TabInfoDetail mTabInfoFloat;
    private IRenderInfoBase mIRenderInfoBase;
    /**
     * 底部菜单
     */
    private TabInfoDetailMenu mMenu;

    /**
     * adapter管理
     */
    private MultiAdapterManager mMultiAdapterMgr;
    /**
     * 正文数据
     */
    private AppInfoDetail mAppInfoDetail;
    
    // 分享dialog
    private AlertDialog mAlertDialog;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        NTLog.d(TAG, StackTraceUtil.getMethodName()
                + " savedInstanceState=" + (null == savedInstanceState ? "null" : savedInstanceState.toString()));
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        getActivity().setTitle(R.string.infodetail_title);
        mInfoId = getArguments().getString(XoneConsts.BUNDLE_KEY.INFO_ID);
        mAppInfoDetail = null;
        mIndex = TransactionGetInfoCfp.TYPE_COMMENT;
        if (null != savedInstanceState) {
            mIndex = savedInstanceState.getInt("index", TransactionGetInfoCfp.TYPE_COMMENT);
        }
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        NTLog.d(TAG, StackTraceUtil.getMethodName()
                + " savedInstanceState=" + (null == savedInstanceState ? "null" : savedInstanceState.toString()));
        View root = View.inflate(getActivity(), R.layout.fragment_infodetail, null);
        
        /**
         * 初始化菜单
         */
        mMenu = (TabInfoDetailMenu)root.findViewById(R.id.infodetail_menu);
        mMenu.setOnTabSelectListener(new OnTabSelectListener() {

            @Override
            public void onTabSelected(View tabView, int index) {
                onMenuSelected(tabView, index);
            }

            @Override
            public void onTabReSelected(View tabView, int index) {
                onMenuSelected(tabView, index);
            }
            
        });
        mMenu.enableClick(false);
        
        /**
         * 初始化导航区域
         */
        mTabInfoFloat = (TabInfoDetail)root.findViewById(R.id.float_comment_tab);
        mTabInfoHead = new TabInfoDetail(getActivity().getApplicationContext());
        mTabInfoFloat.setOnTabSelectListener(mTabSelectListener);
        mTabInfoHead.setOnTabSelectListener(mTabSelectListener);
        
        /**
         * 初始化listview
         */
        mListView = (LoadingListView)root.findViewById(R.id.loading_list);
        View header = View.inflate(getActivity(), R.layout.item_detail_info_base, null);
        mIRenderInfoBase = new RenderInfoBase(header);
        mListView.getRefreshableView().addHeaderView(header);
        // 添加固定的Tab
        mListView.setPinnedHeaderIndex(1);// 设置固定Header的位置
        mListView.getRefreshableView().addHeaderView(mTabInfoHead);
        mListView.setOnPinnedHeaderListener(new OnPinnedHeaderListener() {

            @Override
            public void onPinnedHeaderShow() {
                mTabInfoFloat.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPinnedHeaderHide() {
                mTabInfoFloat.setVisibility(View.GONE);
            }
        });
        mListView.setOnLoadingListener(new OnLoadingListener() {

            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoading() {
                if (null == mAppInfoDetail) {
                    return;
                }
                
                // 加载评论、转发和赞数据
                getInfoCfp(mIndex, mAppInfoDetail.getTime());
            }

            @Override
            public void onLoadingMore() {
                switch (mIndex) {
                    case TransactionGetInfoCfp.TYPE_COMMENT: {
                        AdapterInfoComment adapter = (AdapterInfoComment)mMultiAdapterMgr.getAdapter(0);
                        if (adapter.getCount() > 0) {
                            getInfoCfp(mIndex, adapter.getItem(adapter.getCount() - 1).time);
                        }
                        break;
                    }
                    case TransactionGetInfoCfp.TYPE_FORWARD:{
                        AdapterInfoForward adapter = (AdapterInfoForward)mMultiAdapterMgr.getAdapter(1);
                        if (adapter.getCount() > 0) {
                            getInfoCfp(mIndex, adapter.getItem(adapter.getCount() - 1).time);
                        }
                        break;
                    }
                    case TransactionGetInfoCfp.TYPE_PRAISE:{
                        AdapterInfoPraise adapter = (AdapterInfoPraise)mMultiAdapterMgr.getAdapter(2);
                        if (adapter.getCount() > 0) {
                            getInfoCfp(mIndex, adapter.getItem(adapter.getCount() - 1).time);
                        }
                        break;
                    }
                }
            }
        });
        // 去除分割线
        mListView.getRefreshableView().setDivider(null);
        mListView.getRefreshableView().setDividerHeight(0);
        // 禁止下拉刷新
        mListView.disablePullToRefresh();
        mListView.load();
        
        mMultiAdapterMgr = new MultiAdapterManager(mListView);
        XoneService.getInstance().addListener(mCallBack);
        getInfoDetail();
        return root;
    }
    
    // 评论、转发和赞被点击时响应
    private OnTabSelectListener mTabSelectListener = new OnTabSelectListener() {

        @Override
        public void onTabSelected(View tabView, int index) {
            NTLog.d(TAG, StackTraceUtil.getMethodName() + " index=" + index);
            mIndex = index + 1;
            mMultiAdapterMgr.setCurrentAdapter(index);
            if (tabView == mTabInfoFloat) {
                mTabInfoHead.setCurrentTab(index);
            } else if (tabView == mTabInfoHead) {
                mTabInfoFloat.setCurrentTab(index);
            }
            
            int count = getCountAndShowNoContent(mIndex);
            
            if (count > 0 && 0 == mMultiAdapterMgr.getAdapter(index).getCount()) {
                mListView.reLoad();
            } 
            
        }

        @Override
        public void onTabReSelected(View tabView, int index) {
            
        }

    };
    
    private int getCountAndShowNoContent(int index){
        int count = 0;
        switch (index) {
            case TransactionGetInfoCfp.TYPE_COMMENT:
                count = mAppInfoDetail.getCommentCount();
                break;
            case TransactionGetInfoCfp.TYPE_FORWARD:
                count = mAppInfoDetail.getForwardCount();
                break;
            case TransactionGetInfoCfp.TYPE_PRAISE:
                count = mAppInfoDetail.getPraiseCount();
                break;
        }
        
        if (count == 0) {
            mListView.onNoContent(getString(R.string.infodetail_comment_null));
        }
        
        return count;
    }
    
    private void onMenuSelected(View tabView, int index) {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " index=" + index);
        ParcelableArgument arg = null;
        if (!XoneApp.getAppInstance().isLoginUser(getActivity())) {
            return;
        }
        
        switch (index) {
            case Menu.comment:
                arg = new ParcelableArgument(ParcelableArgument.TYPE_COMMENT);
                arg.mInfoId = mInfoId;
                ActivityDiscuss.launch(getActivity(), arg);
                break;
            case Menu.forward:
                arg = new ParcelableArgument(ParcelableArgument.TYPE_FORWARD);
                arg.mInfoId = mInfoId;
                ActivityDiscuss.launch(getActivity(), arg);
                break;
            case Menu.praise:
                mTid = XoneService.getInstance().doPraiseInfo(mInfoId, !mPraiseFlag);
                mReqList.add(mTid);
                showCustomDialog(getActivity(), getString(R.string.infodetail_praise_tip), mOnCustomDlgCancelListener);
                break;
            case Menu.more:
                // 不同类别生产不同菜单
                List<String> list = null;
                if (AppInfo.TYPE_DISCUSS == mInfoType) {
                    list = Arrays.asList((getResources().getStringArray(R.array.menu_discuss)));
                } else {
                    list = Arrays.asList((getResources().getStringArray(R.array.menu_office)));
                }
                new InfoDetailMoreMenu(getActivity(), this, list, 0);
                break;
        }
    }
    
    private OnCustomDlgCancelListener mOnCustomDlgCancelListener = new OnCustomDlgCancelListener(){

        @Override
        public void onCancel() {
            XoneService.getInstance().cancelTransaction(mTid);
        }  
    };
    
    private void getInfoDetail() {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " mInfoId=" + mInfoId);
        int tid = XoneService.getInstance().doGetInfoDetail(mInfoId);
        mReqList.add(tid);
    }
    
    private void getInfoCfp(int index, long time) {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " index=" + index + " time=" + time);
        PageParam param = new PageParam();
        param.maxTime = String.valueOf(time);
        param.count = XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT;
        int tid = XoneService.getInstance().doGetInfoCfp(mInfoId, index, param);
        mReqList.add(tid);
    }
    
    private void updateInfoDetail(AppInfoDetail value) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        if (null == value) {
            mListView.onLoadingError();
            return;
        }
        
        mPraiseFlag = value.getPraiseFlag();
        mInfoType = value.getInfoType();
        mAppInfoDetail = value;
        mMenu.enableClick(true);
        /**
         * 初始化信息
         */
        BaseAdapter adapter = null;
        int count = 0;
        for (int index = TransactionGetInfoCfp.TYPE_COMMENT; index <= TransactionGetInfoCfp.TYPE_PRAISE; index++) {
            adapter = null;
            switch (index) {
                case TransactionGetInfoCfp.TYPE_COMMENT:
                    adapter = new AdapterInfoComment(getActivity().getApplicationContext());
                    count = mAppInfoDetail.getCommentCount();
                    break;
                case TransactionGetInfoCfp.TYPE_FORWARD:
                    adapter = new AdapterInfoForward(getActivity().getApplicationContext());
                    count = mAppInfoDetail.getForwardCount();
                    break;
                case TransactionGetInfoCfp.TYPE_PRAISE:
                    adapter = new AdapterInfoPraise(getActivity().getApplicationContext());
                    count = mAppInfoDetail.getPraiseCount();
                    break;
            }
            
            if (null != adapter) {
                mMultiAdapterMgr.addAdapter(adapter);
            }
            
            if (mIndex == index && count > 0) {
                getInfoCfp(mIndex, mAppInfoDetail.getTime());
            } else {
                mListView.onLoadingComplete(false);
            }
        }
        
        /**
         * 设置评论、转发和赞数字
         */
        mTabInfoHead.setText(0, mAppInfoDetail.getCommentCount());
        mTabInfoHead.setText(1, mAppInfoDetail.getForwardCount());
        mTabInfoHead.setText(2, mAppInfoDetail.getPraiseCount());
        
        mTabInfoFloat.setText(0, mAppInfoDetail.getCommentCount());
        mTabInfoFloat.setText(1, mAppInfoDetail.getForwardCount());
        mTabInfoFloat.setText(2, mAppInfoDetail.getPraiseCount());
        
        /**
         * 设置赞的状态
         */
        int resId = mPraiseFlag ? R.drawable.icon_toolbar_liked_selector : R.drawable.icon_toolbar_like_selector;
        mMenu.setImageResource(2, resId);
        
        mIRenderInfoBase.renderView(getActivity(), mAppInfoDetail);
        mMultiAdapterMgr.setCurrentAdapter(mIndex-1);
        getCountAndShowNoContent(mIndex);
    }
    
    private void updateInfoCfp(Object obj) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        if (null == obj) {
            mListView.onLoadingError();
            return;
        }
        
        if (obj instanceof List<?>) {
            List<?> list = (List<?>)obj;
            if (list.size() > 0) {
                Object item = list.get(0);
                if (item instanceof InfoComment) {
                    List<InfoComment> list1 = (List<InfoComment>)obj;
                    AdapterInfoComment adapter = (AdapterInfoComment)mMultiAdapterMgr.getAdapter(0);
                    adapter.addTail(list1);
                    adapter.notifyDataSetChanged();
                    if (adapter.getCount() >= mAppInfoDetail.getCommentCount()) {
                        mListView.onLoadingComplete(false);
                    } else {
                        mListView.onLoadingComplete(true);
                    }
                } else if (item instanceof InfoForward) {
                    List<InfoForward> list1 = (List<InfoForward>)obj;
                    AdapterInfoForward adapter = (AdapterInfoForward)mMultiAdapterMgr.getAdapter(1);
                    adapter.addTail(list1);
                    adapter.notifyDataSetChanged();
                    if (adapter.getCount() >= mAppInfoDetail.getForwardCount()) {
                        mListView.onLoadingComplete(false);
                    } else {
                        mListView.onLoadingComplete(true);
                    }
                } else if (item instanceof InfoPraise) {
                    List<InfoPraise> list1 = (List<InfoPraise>)obj;
                    AdapterInfoPraise adapter = (AdapterInfoPraise)mMultiAdapterMgr.getAdapter(2);
                    adapter.addTail(list1);
                    adapter.notifyDataSetChanged();
                    if (adapter.getCount() >= mAppInfoDetail.getPraiseCount()) {
                        mListView.onLoadingComplete(false);
                    } else {
                        mListView.onLoadingComplete(true);
                    }
                }
            }
        }
    }
    
    private void updateInfoPraise(Object obj) {
        boolean praiseFlag = false;
        if (null != obj) {
            praiseFlag = true;
        }
        
        // 停止进度，更新赞状态
        closeCustomDialog();
        int resId = praiseFlag ? R.drawable.icon_toolbar_liked_selector : R.drawable.icon_toolbar_like_selector;
        mPraiseFlag = praiseFlag;
        mMenu.setImageResource(2, resId);
        
        // 更新赞数字，更新赞列表
        if (praiseFlag) {
            mAppInfoDetail.setPraiseCount(mAppInfoDetail.getPraiseCount() + 1);
        } else {
            mAppInfoDetail.setPraiseCount(mAppInfoDetail.getPraiseCount() - 1);
        }
        mTabInfoHead.setText(2, mAppInfoDetail.getPraiseCount());
        mTabInfoFloat.setText(2, mAppInfoDetail.getPraiseCount());
        getInfoCfp(TransactionGetInfoCfp.TYPE_PRAISE, mAppInfoDetail.getTime());
    };
    
    /**
     * 初始化分享dialog里面的自定义view
     * @param view
     */
    private void initShareView(View view) {
        String id = "";
        final String userKey = ManagerAccount.getInstance().getCurrentAccountName();
        TextView tv = null;
        int resIdentifier = 0;
        for (int i = 1; i <= 8; i++) {
            id = "share" + i;
            resIdentifier = getResources().getIdentifier(id, "id", getActivity().getPackageName());
            
            tv = (TextView)view.findViewById(resIdentifier);
            tv.setTag(i);
            
            tv.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    NTLog.d(TAG, StackTraceUtil.getMethodName());
                    
                    ShareBind bind = null;
                    int index = v.getId();
                    switch (index) {
                        // 网易微博
                        case R.id.share1:
                            bind = ManagerShareBind.getShareBind(userKey, ShareType.Netease);
                            mShareType = ShareType.Netease;
                            break;
                        // 人人
                        case R.id.share2:
                            bind = ManagerShareBind.getShareBind(userKey, ShareType.Renren);
                            mShareType = ShareType.Renren;
                            break;
                        // 邮件
                        case R.id.share3:
                            return;
                        // 新浪微博
                        case R.id.share4:
                            bind = ManagerShareBind.getShareBind(userKey, ShareType.Sina);
                            mShareType = ShareType.Sina;
                            break;
                        // 微信好友
                        case R.id.share5:
                            return;
                        // 短信
                        case R.id.share6:
                            return;
                        // 腾讯微博
                        case R.id.share7:
                            bind = ManagerShareBind.getShareBind(userKey, ShareType.Qqmblog);
                            mShareType = ShareType.Qqmblog;
                            break;
                        // QQ空间
                        case R.id.share8:
                            bind = ManagerShareBind.getShareBind(userKey, ShareType.Tencent);
                            mShareType = ShareType.Tencent;
                            break;
                    }
                    
                    if (null == bind || null != bind && !bind.isValid()) {
                    	bind(mShareType);
                    } else {
                    	launchShare(mShareType);
                    }
                }
            });
        }
    }
    
    /**
     * 跳转到授权界面
     * @param item
     */
    private void bind(ShareType type) {
        if (null == type) {
            return;
        }
        
        ActivityWBBind.launch(this, type.value());
    }
    
    /**
     * 启动分享界面
     * @param type
     */
    private void launchShare(ShareType type) {
    	ActivityShare.launch(getActivity(), type.value());
    }
 
    @Override
    protected void onLeftTopBack() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        getActivity().finish();
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        outState.putInt("index", mIndex);
        super.onSaveInstanceState(outState);
    }
    
    @Override
    public void onClick(View v) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        switch (v.getId()) {
            // 菜单分享
            case InfoDetailMoreMenu.MENU_SHARE:
                View view = View.inflate(getActivity(), R.layout.view_share, null);
                initShareView(view);
                mAlertDialog = CustomAlertDialog.showAlertDialog(getActivity(), 0, R.string.detail_share_title, -1, -1, view, -1, null);
                break;
            // 菜单反馈或举报
            case InfoDetailMoreMenu.MENU_OTHER:
                if (AppInfo.TYPE_DISCUSS == mInfoType) {
                    ActivityDetailMenuContainer.launch(getActivity(), ActivityDetailMenuContainer.TYPE_REPORT, mInfoId, mAppInfoDetail.getUser().getNickname());
                } else {
                    ActivityDetailMenuContainer.launch(getActivity(), ActivityDetailMenuContainer.TYPE_FEEDBAK, mInfoId, mAppInfoDetail.getUser().getNickname());
                }
                break;
        }
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (resultCode == Activity.RESULT_OK) {
    		// 关闭分享选择器
    		if (null != mAlertDialog && mAlertDialog.isShowing()) {
    			mAlertDialog.dismiss();
    			mAlertDialog = null;
    		}
    		// 启动写分享界面
    		launchShare(mShareType);
    	}
    }
    
    @Override
    public void onDestroy() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        XoneService.getInstance().removeListener(mCallBack);
        mCallBack = null;
        super.onDestroy();
        mReqList.clear();
        mListView = null;
        mTabInfoHead = null;
        mTabInfoFloat = null;
        mTabSelectListener = null;
        mMenu = null;
        mMultiAdapterMgr.clear();
        mMultiAdapterMgr = null;
    }

    private XoneCallBack mCallBack = new XoneCallBack() {

        @Override
        public void onInfoDetail(int transactionId, Object obj) {
            if (mReqList.remove(Integer.valueOf(transactionId))) {
                if (null != obj && obj instanceof AppInfoDetail) {
                    updateInfoDetail((AppInfoDetail)obj);
                }
            }
        };

        @Override
        public void onInfoDetailError(int transactionId, int errCode, String err) {
            if (mReqList.remove(Integer.valueOf(transactionId))) {
                updateInfoDetail(null);
            }
        };
        
        @Override
        public void onInfoCfp(int transactionId, Object obj) {
            if (mReqList.remove(Integer.valueOf(transactionId))) {
                updateInfoCfp(obj);
            }
        };
        
        @Override
        public void onInfoCfpError(int transactionId, int errCode, String err) {
            if (mReqList.remove(Integer.valueOf(transactionId))) {
                updateInfoCfp(null);
            }
        };
        
        @Override
        public void onPraiseInfo(int transactionId, Object obj) {
            if (mReqList.remove(Integer.valueOf(transactionId))) {
                updateInfoPraise(obj);
            }
        };
        
        @Override
        public void onPraiseInfoError(int transactionId, int errCode, String err) {
            if (mReqList.remove(Integer.valueOf(transactionId))) {
            }
        };
        
        
    };
    
}
